package com.nowcoder.Offer.List;

import org.junit.Test;

import java.util.HashSet;

/**
 * 找到链表的环
 */
public class LoopOfList {

    public ListNode EntryNodeOfLoop(ListNode pHead){
        HashSet<ListNode> set = new HashSet<>();

        set.add(pHead);

        while (pHead.next!=null){
            pHead = pHead.next;
            if(set.contains(pHead)) return pHead;
            set.add(pHead);
        }
        return null;
    }

    @Test
    public void test(){
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);

        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = node3;

        System.out.println(EntryNodeOfLoop(node1).val);
    }
}
